﻿#include "CodeProcess.h"
#include "UDPApi.h"

CodeProcess::CodeProcess(MediaInfo *media)
{
		mediainfo = media;		
}

CodeProcess::~CodeProcess()
{
	StopThread();
}

void CodeProcess::ProcessCode()
{
	memset(&rtpinfo, 0, sizeof(rtpinfo));
	memset(&rtpinfo1, 0, sizeof(rtpinfo1));
	//解码
		
		if(mediainfo->rtpque_put.size()>2)
		{
			mediainfo->rtpmutex_put.Lock();
			memcpy(&rtpinfo,&(mediainfo->rtpque_put.front()),sizeof(RTP_INFO));
			mediainfo->rtpque_put.pop_front();
			mediainfo->rtpmutex_put.Unlock();
			//printf("before decode = %d\n",rtpinfo.PayLoadLen);
			m_app.decPayload(rtpinfo);
			//printf("after decode = %d\n",rtpinfo.PayLoadLen);


			//mediainfo->rtpmutex_put.Lock();
			//memcpy(&rtpinfo1, &(mediainfo->rtpque_put.front()), sizeof(RTP_INFO));
			//mediainfo->rtpque_put.pop_front();
			//mediainfo->rtpmutex_put.Unlock();
			//printf("before decode = %d\n", rtpinfo1.PayLoadLen);
			//m_app.decPayload(rtpinfo1);
			//printf("after decode = %d\n", rtpinfo.PayLoadLen);
			//rtpinfo.PayLoadLen += rtpinfo1.PayLoadLen;
			//memcpy(rtpinfo.DecData + rtpinfo1.PayLoadLen, rtpinfo1.DecData, rtpinfo1.PayLoadLen*sizeof(short));


			//time_t t;
			//time(&t);
			//FILE *fp=fopen("decode.txt","a");
			//fprintf(fp, "%s======encode rtp len= %d\n", ctime(&t), rtpinfo.PayLoadLen);
			//fclose(fp);
			
			mediainfo->rtpmutex_put.Lock();
			//printf("total len = %d\n", rtpinfo.PayLoadLen);

			//FILE * fp = fopen("recvaudio", "ab+");
			//fwrite(rtpinfo.DecData, sizeof(short), rtpinfo.PayLoadLen, fp);
			//fclose(fp);

		//	mediainfo->getmutex.Lock();
			mediainfo->getque.push_back(rtpinfo);
			mediainfo->rtpmutex_put.Unlock();

			//printf("解码结束\n");
		}
		

		//return;
		memset(&rtpinfo,0,sizeof(rtpinfo));
//编码
		
		if (mediainfo->putque.size()>0)
		{	
			mediainfo->rtpmutex_put.Lock();
			//printf("mediainfo->putque.size = %d\n",mediainfo->putque.size());
			memcpy(&rtpinfo,&(mediainfo->putque.front()),sizeof(RTP_INFO));
			mediainfo->putque.pop_front();
			mediainfo->rtpmutex_put.Unlock();
			//printf("encode rtp len= %d curtimestamp=%ld\n", rtpinfo.PayLoadLen, GetTickCount());
			
			
			//time_t t;
			//time(&t);
			//FILE *fp=fopen("encodec.txt","a");
			//fprintf(fp, "%s======encode rtp len= %d\n", ctime(&t), rtpinfo.PayLoadLen);
			//fclose(fp);

			m_app.encodePayload(rtpinfo);

			mediainfo->rtpmutex_put.Lock();
			mediainfo->rtpque_get.push_back(rtpinfo);
			mediainfo->rtpmutex_put.Unlock();
//			printf("编码结束\n");
		}
		return ;
}

int CodeProcess::CreateThread()
{
	int ret = 0;
	code = new CodeThread(*this);
	if (code == NULL)
	{
		return -1;
	}
	if ((ret = code->Start())<0)
	{
		return ret;
	}
	return ret;
}
int CodeProcess::StopThread()
{
	if (code != NULL)
	{
		delete code;
		code = NULL;
	}
	return 0;
}